package com.example.finallyjob.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.finallyjob.dao.UserImp;
import com.example.finallyjob.entity.Info;
import com.example.finallyjob.entity.User;
import com.example.finallyjob.tool.MD5Unit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;


@Service
public class UserService {
    Logger logger= LoggerFactory.getLogger(getClass());
    @Autowired
    private UserImp userImp;
    @Autowired
    private MongoTemplate mongoTemplate;

    @ApiOperation(value = "登录",notes = "返回用户信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "name", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "password", value = "用户密码", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "status", value = "用户登录状态码(1表示用户登录||10表示管理员登录)", required = true, dataType = "String")
    })
    public User login(String username,String password,String status) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        password= new MD5Unit().encodePassword(password);
        User user=new User(username,password,status,null,null);
        User login = userImp.login(user);
        if(login != null){
            if (login.getUserPass().equals(password) && !(login.getStatus().equals("0"))){
                Query query=new Query(new Criteria("userId").is(login.getUserId()));
                User users = mongoTemplate.findOne(query, User.class);
                if(users == null){
                    mongoTemplate.insert(login);
                }else{
                    login.setArticleId(users.getArticleId());
                    login.setFriend(users.getFriend());
                    login.setVideoId(users.getVideoId());
                }
                return login;
            }
        }
        return null;
    }

//注册
@ApiOperation(value = "注册",notes = "返回用户信息")
@ApiImplicitParams({
        @ApiImplicitParam(paramType = "query", name = "name", value = "用户名", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "password", value = "用户密码", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "status", value = "用户注册状态码(1表示用户注册||0表示管理员注册)", required = true, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "Img", value = "图片的编号", required = false, dataType = "String"),
        @ApiImplicitParam(paramType = "query", name = "label", value = "用户简介", required = false, dataType = "String")
})
    @Transactional(rollbackFor = Exception.class)
    public User register(String username,String password,
                         String status,String Img,String label) throws Exception {
        password= new MD5Unit().encodePassword(password);
        System.out.println(password);
        User user=new User(username,password,status,Img,label);
        if(status.equals("1")){
            if (userImp.RegsityUser(user)<1){
                throw new Exception();
            }
        }else {
            if(userImp.RegsityAdmin(user)<1){
                throw new Exception();
            }
            Date date=new Date();
            mongoTemplate.insert(new Info(user.getUserName(),"6",
                    String.valueOf(user.getUserId()), null,
                    "user",new Timestamp(new Date(date.getYear(),date.getMonth(),
                    date.getDate()).getTime()),516));
        }

        return user;
    }

    @ApiOperation("通过管理员申请")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "name", value = "用户id号", required = true, dataType = "Integer")
    })
    public Boolean agree(Integer id){
        User user=new User();
        user.setUserId(id);
        user.setStatus("10");
        int result=userImp.agree(user);
        if(result>0) {
            return true;
        }
        else
            return false;
    }

    @ApiOperation(value = "修改个人头像和简介信息",notes = "返回更新后的个人头像简介信息")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "query", name = "id", value = "用户名", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "status", value = "用户注册状态码(1表示用户||10表示管理员)", required = true, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "Img", value = "图片的编号", required = false, dataType = "String"),
            @ApiImplicitParam(paramType = "query", name = "label", value = "用户简介", required = false, dataType = "String")
    })
    public User updata(String status, Integer id, String img, String label){
        User user=new User();
        user.setStatus(status);
        user.setImg(img);
        user.setUserId(id);
        user.setLabel(label);
        if(img != null || label!=null)
        {
        if (userImp.Updata(user) > 0) {
            System.out.println("insert succeese");
            return user;
        } else
            return null;
        }else {
            return null;
        }
    }

    public List<Info> FindInfo(Integer id){
        Query query=new Query(new Criteria("userid").is(id));
        List<Info> list=mongoTemplate.find(query,Info.class);
        return list;
    }

    @Transactional(rollbackFor = Exception.class)
    public String UserDelect(String num, int id,
    String status, String userText, String userVideo) throws Exception {
        if(userText != null){
            userText=userText.replace("\\","");
        }else {
            userVideo=userVideo.replace("\\","");
        }
        String i=Delete(num,status,userText,userVideo);
        if(i != null){
            Query query = new Query(Criteria.where("userId").is(id));
            Update update = new Update();
            if (status.equals("text")) {
                update.set("articleId", i);
                mongoTemplate.upsert(query, update, User.class);
            } else {
                update.set("videoId", i);
                mongoTemplate.upsert(query, update, User.class);
            }
            return i;
        }
        return null;
    }

    @Transactional(rollbackFor = Exception.class)
    public String adminDelect(String num, int id, String status) throws Exception {
        Query query=new Query(new Criteria("userId").is(id));
        User user=mongoTemplate.findOne(query,User.class);
        String i=Delete(num,status,user.getArticleId(),user.getVideoId());
        if(i != null){
            Update update = new Update();
            if (status.equals("text")) {
                update.set("articleId", i);
                mongoTemplate.upsert(query, update, User.class);
            } else {
                update.set("videoId", i);
                mongoTemplate.upsert(query, update, User.class);
            }
            return i;
        }
        return null;
    }

    public String Delete(String num,String status,
                         String userText,String userVideo) throws Exception {
        if(status.equals("text")) {
            JSONObject object = JSON.parseObject(userText);
            object.remove(num);
            if(userImp.DeleteT(num)<1){
                throw new Exception();
            }
            return object.toString();
        }else {
            JSONObject object = JSON.parseObject(userVideo);
            object.remove(num);
            if(userImp.DeleteV(num)<1){
                throw new Exception();
            }
            return object.toString();
        }
    }


}
